// packageA/pages/partsOrderAdd/partsOrderAdd.js
const app = getApp();
import CommonService from '../../../utils/service/commonService.js';
import Toast from '../../../miniprogram_npm/@vant/weapp/toast/toast';
import Dialog from '../../../miniprogram_npm/@vant/weapp/dialog/dialog';
const util = require('../../../utils/util');
import Base64 from '../../../utils/Base64.js';

Page({

  /**
   * 页面的初始数据
   */
  data: {
    //传参
    paramObj:null,
    //传参来的id
    id:null,
    //是否是修改
    isEdit:false,
    //修改信息回显
    editInfo:{},
    //提交按钮禁用
    disabled:false,
    //避免表单重复提交
    code:null,
    //选择框
    showSelect:false,
    //选择数据
    selectList:[],
    //当前选择
    selectField:'',
    //选择框标题
    selectTitle:'',
    //显示选择搜索框
    showSelectSearch:false,
    //搜索词
    valueSearch:'',  
    //配件列表
    partList:[],
    //厂家设备型号
    factoryCategory:null,
    citiesName:['请选择省','市','区'],
    //采购类型（用于判断客户信息必填）
    purchaseId:null,
    //当前登录账号
    user:null,
    //设置部门用友编码
    showDepartCode:false,
    //部门名称
    departName:'',
    //部门用友编码
    departCode:null,
    //设置人员用友编码
    showStaffCode:false,
    //人员用友编码
    staffCode:null,
    //用户权限
    authority:null
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    wx.getUserProfile({
      desc: '为您提供更好的服务',
      success: (res) => {}
    })
    
    this.setData({
      user:app.globalData.userInfo,
      code:Base64.encode(new Date() + app.globalData.userInfo.userName),
      authority:app.globalData.authority
    })

    //获取当前用户的用友编码
    this.getUserInfo();  

    if(options.paramObj){
      let paramObj=JSON.parse(options.paramObj);
      console.log('添加配件采购传参');
      console.log(paramObj);

      this.setData({
        paramObj: paramObj
      })

      if(paramObj.id){
        this.setData({
          id: paramObj.id,
          isEdit:true
        })
        //获取修改的数据
        this.getInfo();
      }
    }
   
    //获取厂家设备型号
    this.getFactoryEquipmentModel();
  },

  //获取当前用户的用友编码
  getUserInfo(){
    let param = {
      isAuth: false,
      className: 'user',
      data: {
        id: this.data.user.id,
        selectFields: ['id','userName','code']
      }
    }

    CommonService.goFindList(param).then(res=>{
      if(res.data.data && res.data.data.result && res.data.data.result.length){
        let result=res.data.data.result[0];
        
        let code='user.code';
        this.setData({
          [code]: result.code ? result.code : null
        })
      }
    }).catch((error) => {
    })
  },

  //提交表单
  confirmForm(e){
    //避免表单重复提交-先禁用按钮
    this.setData({
      disabled:true
    })
    
    let obj=e.detail.value;
    let td=this.data;
    let editInfo=td.editInfo;
    let partList=td.partList;
    let user=td.user;
    
    //服务方必填
    if(!editInfo.server){
      Toast.fail('请选择服务方');
      return;
    }

    //采购类型必填
    if(!editInfo.purchaseClassify){
      Toast.fail('请选择采购类型');
      return;
    }

    //收货人必填
    let consigneeName=obj.consigneeName.trim();
    if(!this.formNotEmpty(consigneeName,'consigneeNameMessage','请输入收货人')){
      return;
    }

    //收货人电话
    let consigneePhone=obj.consigneePhone.trim();
    if(!this.formNotEmpty(consigneePhone,'consigneePhoneMessage','请输入收货人电话')){
      return;
    }

    //手机号格式
    if(!util.checkPhoneFormat(consigneePhone)){
      this.setData({
        consigneePhoneMessage: '手机号格式错误',
        disabled: true
      })
      return;
    }  

    //详细地址必填
    let address=obj.address.trim();
    if(!this.formNotEmpty(address,'addressMessage','请输入详细地址')){
      return;
    }

    //配件厂家必填 
    if(!editInfo.factory){
      Toast.fail('请选择配件厂家');
      return;
    }
    
    let equipmentNo=obj.equipmentNo.trim();
    if(td.purchaseId==131 || td.purchaseId==133 || td.purchaseId==135){
      if(!this.formNotEmpty(equipmentNo,'equipmentNoMessage','请输入设备编码')){
        return;
      }

      //项目必填 
      if(!editInfo.project){
        Toast.fail('请选择项目');
        return;
      }

      //项目用友编码
      if(!editInfo.project.code){
        Toast.fail('请设置项目的用友编码');
        return;
      }
    }    

    if(td.purchaseId==130 || td.purchaseId==131 || td.purchaseId==133 || td.purchaseId==135){
      //客户必填 
      if(!editInfo.clientDepart){
        Toast.fail('请选择结算单位');
        return;
      }

      //客户用友编码
      if(!editInfo.clientDepart.code){
        Toast.fail('请设置客户的用友编码');
        return;
      }

      //业务员必填 
      if(!editInfo.salesperson){
        Toast.fail('请选择业务员');
        return;
      }
    }

    //配件必填
    if(partList.length && partList[0].name){
    }else{
      Toast.fail('请至少添加一条配件信息');
      return;
    }

    //计算进价总金额
    let total=0;      
    partList.forEach(item => {
      total+=Number(item.purchasingPrice)*item.num;
    });
    
    //计算售价总金额
    let total2=0;      
    partList.forEach(item => {
      total2+=Number(item.salePrice)*item.num;
    });

    let param={
      id: td.id,
      //收货地址
      address: address,
      //平台数据
      appid: [app.globalData.myAppId],
      //审批流
      approvalProcess: editInfo.approvalProcess,
      //地区
      cities: editInfo.cities,
      //地区
      citiesName: td.citiesName[0] +'-'+ td.citiesName[1] +'-'+ td.citiesName[2],
      //收货人
      consignee: {
        name: consigneeName,
        phone: consigneePhone
      },
      //下单人员电话
      contact:user.personalPhone,
      //权限
      dataAuthority:{
        depart: [editInfo.factory.depart, app.globalData.userInfo.depart]
      },
      //设备编码
      equipmentNo: equipmentNo,
      //配件厂家
      factory: {
        id: editInfo.factory.id,
        name: editInfo.factory.name,
        depart: editInfo.factory.depart,
        UFIDACode: editInfo.factory.UFIDACode
      },
      //入库方式
      inStorageType: editInfo.purchaseClassify.inStorage,
      //下单人员-当前登录人员
      orderPersonnel: {
        id: user.id,
        name: user.userName,
        code: user.code,
        phone: user.personalPhone
      },
      //出库类型
      outStorageType:{},
      //采购类型
      purchaseClassify: editInfo.purchaseClassify,
      //配件？？？
      purchaseParts: partList,
      //备注
      remark: obj.remark.trim(),
      //服务方
      server: {
        id: editInfo.server.id,
        name: editInfo.server.name
      },
      //采购人员-写死了
      staff:{
        id: 641,
		    name: "孙秀健",
		    phone: "18522080160",
		    code: "023",
		    passed: 0
      },
      //状态
      state: 2,  
      //进价总金额
      totalPurchasePrice: total,
      //售价总金额
      totalSalePrice: total2  
    } 
    
    //客户
    if(editInfo.clientDepart){
      param.clientDepart={
        id: editInfo.clientDepart.id,
        name: editInfo.clientDepart.name,
        code: editInfo.clientDepart.code
      }
    }

    //项目
    if(editInfo.project){
      param.project={
        id: editInfo.project.id,
        name: editInfo.project.name,
        code: editInfo.project.code
      }
    }

    //业务员
    if(editInfo.salesperson){
      param.salesperson={
        id: editInfo.salesperson.id,
        name: editInfo.salesperson.name,
        code: editInfo.salesperson.code
      }
    } 
    
    if(td.isEdit){
      //当前审批人员
      //currentApprovalMan
      //是否有需要审批配件
      //hasApproval
      //id
      //_id


      //操作记录
      let operation=editInfo.operation;
      operation.push({
        user: app.globalData.userInfo.userName,
        date: util.timeFormat(new Date()),
        log: "修改订单"
      });
      param.operation=operation;

    }else{
      //采购时间
      param.purchasingTime=new Date();

      //操作记录
      param.operation=[{
        user: app.globalData.userInfo.userName,
        date: util.timeFormat(new Date()),
        log: "提交配件采购订单"
      }]

      //入库单号
      let count = util.currentTimestamp();
      let orderNo = 'SH';
      if (editInfo.server.id === 62) {
        orderNo = "SDBN"
      } else if (editInfo.server.id === 63) {
        orderNo = "SDZL"
      } else if (editInfo.server.id === 64) {
        orderNo = "TJZL"
      } else if (editInfo.server.id === 140) {
        orderNo = "ZLHB"
      }
      for (let i = 0; i < 8 - count.toString().length; i++) {
        orderNo += "0";
      }
      orderNo += count;
      param.orderNo = orderNo;
    }

    console.log(param);

    //避免表单重复提交
    // Toast.loading({
    //   duration: 0,
    //   forbidClick: true,
    //   message: '数据提交中...'
    // });  

    //建仓库
    //this.getDepot();

    // CommonService.purchaseSave(param).then(res=>{
    //   this.setData({
    //     disabled:false
    //   })
    //   if (res.statusCode == 200 && res.data.success == true){
    //     Toast.success('成功');
    //     setTimeout(() => {
    //       //返回列表页并刷新数据
    //       this.backAndRefresh();
    //     }, 1000);
    //   }else if(res.statusCode==202){
    //     Toast.fail('您操作太快了,请勿重复提交');
    //   }else{
    //     Toast.fail('操作失败');
    //   }
    // }).catch((error) => {
    //   Toast.fail('操作失败');
    // })  
  },

  //获取修改的数据
  getInfo(){
    let param = {
      isAuth: false,
      className: 'partsPurchaseOrder',
      data: {
        id:this.data.id,
        selectFields: ['id', 'cities', 'totalPurchasePrice', 'remark', 'server', 'staff', 'citiesName', 'freight',
        'state', 'serverId', 'factoryName', 'address', 'purchaseClassify', 'factoryId',
        'operation', 'orderNo', 'contact', 'factory', 'reject', 'serverName', 'parts', 'logistics',
        'equipmentNo', 'salesperson', 'consignee', 'phone', 'clientDepart', 'shippedNum', 'appId', 'outStorageType',
        'inStorageType', 'dataAuthority', 'totalSealPrice', 'project', 'orderPersonnel']
      }
    }

    CommonService.goFindList(param).then(res => {
      if(res.data.data && res.data.data.result && res.data.data.result.length) {
        let result=res.data.data.result[0];
        console.log('采购订单回显');
        console.log(result);

        //处理配件列表
        let list=result.parts;
        list.forEach(item => {
           item.spec=item.part.spec;
        });
        
        this.setData({
          editInfo: result,
          //地区
          citiesName:result.citiesName.split("-"),
          //配件
          partList:list
        })
      }
    }).catch((error) => {
    })
  },

  //显示选择框
  onShowSelect(e){
    this.setData({
      selectList: []
    })
    
    let dataset=e.target.dataset;
    let field=dataset.field;   
    
    this.setData({
      showSelect: true,
      selectField: field
    })

    //查询服务方
    if(field=='server'){
      this.setData({
        selectTitle: '服务方',
        showSelectSearch:false
      })
      this.getServerList();
    }

    //查询采购类型
    if(field=='purchaseClassify'){
      this.setData({
        selectTitle: '采购类型',
        showSelectSearch:false
      })
      this.getPurchaseClassifyList();
    }

    //查询采购人员
    if(field=='staff'){
      this.setData({
        selectTitle: '采购人员',
        showSelectSearch:true
      })
      this.getStaffList();
    }

    //查询配件厂家    
    if(field=='factory'){
      this.setData({
        selectTitle: '配件厂家',
        showSelectSearch:true
      })
      this.getFactoryList();
    }

    //结算单位
    if(field=='client'){
      this.setData({
        selectTitle: '结算单位',
        showSelectSearch:true
      })
      this.getClientList();
    }

    //项目
    if(field=='project'){
      if(this.data.editInfo.clientDepart && this.data.editInfo.clientDepart.id){
        this.setData({
          selectTitle: '项目',
          showSelectSearch:true
        })
        this.getProjectList();
      }else{
        Toast.fail('请先选择结算单位');
      }
    }

    //业务员
    if(field=='salesperson'){
      this.setData({
        selectTitle: '业务员',
        showSelectSearch:true
      })
      this.getSalespersonList();
    }

    //配件
    if(field=='partName'){      
      if(this.data.editInfo.factory){
        this.setData({
          selectTitle: '配件',
          showSelectSearch:false,
          currentIndex: dataset.index,
          currentLoop: dataset.current
        })
        this.getPartList();
      }else{
        this.setData({
          showSelect: false
        })
        Toast.fail('请先选择配件厂家');
      }
    }

    //审批流
    if(field=='approvalProcess'){
      this.setData({
        selectTitle: '审批流',
        showSelectSearch: false
      })
      this.getApprovalList();
    }
  },    

  //隐藏选择框
  onCloseSelect(){
    this.setData({
      showSelect: false
    })
  },

  //确认选项
  onConfirmSelect(e){
    let selectField=this.data.selectField;
    let id=null,name=null,obj=null;

    //服务方
    if(selectField=='server'){
      obj='editInfo.server';
    }

    //采购类型
    if(selectField=='purchaseClassify'){
      obj='editInfo.purchaseClassify';
      
      // 130 采购销售：结算单位，业务员
      // 131 采购赠送：设备编码、结算单位、项目、业务员
      // 132 采购入库：
      // 133 采购维保：设备编码、结算单位、项目、业务员
      // 134 供应商备货：
      // 135 质保售后：设备编码、结算单位、项目、业务员

      this.setData({
        purchaseId:e.detail.value.id
      })
    }

    //采购人员
    if(selectField=='staff'){
      obj='editInfo.staff';
      let val=e.detail.value.obj;
      this.setData({
        [obj]:{
          id:val.id,
          name:val.userName,
          phone:val.personalPhone
        }
      })
    }

    //配件厂家
    if(selectField=='factory'){
      obj='editInfo.factory';

      //查询厂家用友编码
      this.getFactoryCode(e.detail.value.id,e.detail.value.text);
    }

    //客户/结算单位
    if(selectField=='client'){
      obj='editInfo.clientDepart';
    }

    //项目
    if(selectField=='project'){
      obj='editInfo.project';
    }

    //是否有用友编码
    if(selectField=='client' || selectField=='project'){
      let val=e.detail.value.obj;
      if(!val.code){
        this.setData({
          showDepartCode: true,
          departName: e.detail.value.text
        })
      }
    }

    //业务员
    if(selectField=='salesperson'){
      obj='editInfo.salesperson';
      let val=e.detail.value.obj;      
      this.setData({
        [obj]:{
          id:val.id,
          name:val.userName,
          code:val.code ? val.code :null
        }
      }) 
      
      //人员用友编码
      if(!val.code){
        this.setData({
          showStaffCode: true,
          staffName: e.detail.value.text
        })
      }
    } 
    
    //配件
    if(selectField=='partName'){
      let obj=e.detail.value.obj;
      let names=e.detail.value.text;
      let currentIndex=this.data.currentIndex;
      let partList=this.data.partList;

      //名称不能重复
      let flag=partList.some(item=>{
        return item.code==obj.code;
      });
      if(flag){       
        Toast.fail('当前配件已添加，请修改数量');
        return;
      }

      //处理配件列表
      partList.forEach((item,index) => {
        if(index==currentIndex){
          //编码
          item.code=obj.code;
          //名称
          item.name=obj.name;
          //规格
          item.specStr=names.split("&")[1],
          //型号
          item.brandsStr=obj.factories[0].brands[0].name
          //单位
          item.unit=obj.base[0].unit;
          //数量
          item.num=1;
          //进价
          item.purchasingPrice=obj.factories[0].purchasePrice;
          //售价
          item.salePrice=obj.factories[0].salePrice;
          //配件信息
          item.part=obj;
          //其他不知道啥东西
          item.gift = obj.base[0].gift,
          item.approve = obj.base[0].approve
        }
      });

      this.setData({
        partList:partList,
        disabled: false
      })      
    }

    //审批流
    if(selectField=='approvalProcess'){
      obj='editInfo.approvalProcess';
    }

    if(selectField!='partName'){
      this.setData({
        valueSearch: '',
        disabled: false
      })

      if(id && name){
        this.setData({
          [id]:e.detail.value.id,
          [name]:e.detail.value.text
        })
      }

      if(obj && selectField!='staff' && selectField!='salesperson'){
        this.setData({
          [obj]:e.detail.value.obj
        })
      }
    }  
    
    this.onCloseSelect();
  },

  //清除选项
  onCancelSelect(){
    let selectField=this.data.selectField;
    let id=null,name=null,obj=null;

    //服务方
    if(selectField=='server'){
      obj='editInfo.server';
    }

    //采购类型
    if(selectField=='purchaseClassify'){
      obj='editInfo.purchaseClassify';      
    }

    //采购人员
    if(selectField=='staff'){
      obj='editInfo.staff';
    }

    //配件厂家
    if(selectField=='factory'){
      obj='editInfo.factory';
    }

    //客户
    if(selectField=='client'){
      obj='editInfo.clientDepart';
    }

    //项目
    if(selectField=='project'){
      obj='editInfo.project';
    }

    //客户
    if(selectField=='salesperson'){
      obj='editInfo.salesperson';
    }  

    if(id && name){
      this.setData({
        [id]:null,
        [name]:''
      })
    }

    if(obj){
      this.setData({
        [obj]:null
      })
    }
    
    this.onCloseSelect();
  }, 
  
  //选择框搜索
  onChangeSelectVal(e){
    let selectField=this.data.selectField;
    
    this.setData({
      valueSearch: e.detail
    })

    //采购人员
    if(selectField=='staff'){
      this.getStaffList();
    }

    //配件厂家
    if(selectField=='factory'){
      this.getFactoryList();
    }

    //客户
    if(selectField=='client'){
      this.getClientList();
    }

    //项目
    if(selectField=='project'){
      this.getProjectList();
    }

    //业务员
    if(selectField=='salesperson'){
      this.getSalespersonList();
    }
  },

  //查询服务方
  getServerList(){
    let param = {
      isAuth: false,
      className: 'dictionary',
      data: {
        searchAll: true,
        key: 'server',
        selectFields: ['id','name']
      }
    }

    CommonService.goFindList(param).then(res=>{
      if(res.data.data && res.data.data.result && res.data.data.result.length){
        let result=res.data.data.result;
        let arr=[];
        result.forEach(item => {
          arr.push({
            text:item.name,
            id:item.id,
            obj:item
          });
        });
        
        this.setData({
          selectList: arr
        })
      }
    }).catch((error) => {
    })
  },

  //查询采购类型
  getPurchaseClassifyList(){
    let param = {
      isAuth: false,
      className: 'dictionary',
      data: {
        searchAll: true,
        key: 'partsPurchaseClassify',
        selectFields: ['id','name','inStorage','outStorage','receivingParty']
      }
    }

    CommonService.goFindList(param).then(res=>{
      if(res.data.data && res.data.data.result && res.data.data.result.length){
        let result=res.data.data.result;
        let arr=[];
        result.forEach(item => {
          arr.push({
            text:item.name,
            id:item.id,
            obj:item
          });
        });
        this.setData({
          selectList: arr
        })
      }
    }).catch((error) => {
    })
  },

  //查询采购人员
  getStaffList(){
    this.setData({
      selectList: []
    })

    let param = {
      isAuth: true,
      className: 'user',
      data: {
        searchAll: true,
        type: 1,
        selectFields: ['id','userName','personalPhone']
      }
    }

    //模糊查询
    if(this.data.valueSearch){
      param.data.userName='%' + this.data.valueSearch + '%';
    }

    CommonService.goFindList(param).then(res=>{
      if(res.data.data && res.data.data.result && res.data.data.result.length){
        let result=res.data.data.result;
        let arr=[];
        result.forEach(item => {
          arr.push({
            text:item.userName,
            id:item.id,
            obj:item
          });
        });
        this.setData({
          selectList: arr
        })
      }
    }).catch((error) => {
    })
  },

  //查询配件厂家
  getFactoryList(){
    this.setData({
      selectList: []
    })

    let param = {
      isAuth: true,
      className: 'supplierFactories',
      data: {
        searchAll: true,
        type: [75, 76],
        selectFields: ['id','name','factoryDepart']
      }
    }

    //模糊查询
    if(this.data.valueSearch){
      param.data.name='%' + this.data.valueSearch + '%';
    }

    CommonService.goFindList(param).then(res=>{
      if(res.data.data && res.data.data.result && res.data.data.result.length){
        let result=res.data.data.result;
        let arr=[];
        result.forEach(item => {
          arr.push({
            text:item.name,
            id:item.id,
            obj:{
              id:item.id,
              name:item.name,
              depart:item.factoryDepart
            }
          });
        });
        this.setData({
          selectList: arr
        })
      }
    }).catch((error) => {
    })
  },  

  //查询客户
  getClientList(){
    this.setData({
      selectList: []
    })

    let param = {
      isAuth: true,
      className: 'depart',
      data: {
        searchAll: true,
        level: 1,
        type: 4,
        selectFields: ['id','name','code'],
        sort: {id: 1}
      }
    }

    //模糊查询
    if(this.data.valueSearch){
      param.data.name='%' + this.data.valueSearch + '%';
    }

    CommonService.goFindList(param).then(res=>{
      if(res.data.data && res.data.data.result && res.data.data.result.length){
        let result=res.data.data.result;
        let arr=[];
        result.forEach(item => {
          arr.push({
            text:item.name,
            id:item.id,
            obj:item
          });
        });
        this.setData({
          selectList: arr
        })
      }
    }).catch((error) => {
    })
  },

  //查询项目
  getProjectList(){
    this.setData({
      selectList: []
    })

    let param = {
      isAuth: true,
      className: 'depart',
      data: {
        searchAll: true,
        id:{
          '!=':this.data.editInfo.clientDepart.id
        },
        isProject: true,
        selectFields: ['id','name','code'],
        sort: {id: 1}
      }
    }

    //模糊查询
    if(this.data.valueSearch){
      param.data.name='%' + this.data.valueSearch + '%';
    }

    CommonService.goFindList(param).then(res=>{
      if(res.data.data && res.data.data.result && res.data.data.result.length){
        let result=res.data.data.result;
        let arr=[];
        result.forEach(item => {
          arr.push({
            text:item.name,
            id:item.id,
            obj:item
          });
        });
        this.setData({
          selectList: arr
        })
      }
    }).catch((error) => {
    })
  },

  //查询业务员
  getSalespersonList(){
    this.setData({
      selectList: []
    })

    let param = {
      isAuth: true,
      className: 'user',
      data: {
        searchAll: true,
        type: 1,
        selectFields: ['id','userName','code']
      }
    }

    //模糊查询
    if(this.data.valueSearch){
      param.data.userName='%' + this.data.valueSearch + '%';
    }

    CommonService.goFindList(param).then(res=>{
      if(res.data.data && res.data.data.result && res.data.data.result.length){
        let result=res.data.data.result;
        let arr=[];
        result.forEach(item => {
          arr.push({
            text:item.userName,
            id:item.id,
            obj:item
          });
        });
        this.setData({
          selectList: arr
        })
      }
    }).catch((error) => {
    })
  },

  //查询配件
  getPartList(){
    let param = {
      isAuth: false,
      className: 'partsFactory',
      data: {
        factoryIds: this.data.editInfo.factory.id,
        used: true,
        disabled: false,
        searchAll: true,
        selectFields: ['id', 'params', 'specs', 'name', 'code', 'factories', 'used', 'disabled', 'partsId', 'base']
      }
    }

    CommonService.goFindList(param).then(res=>{      
      if(res.data.data && res.data.data.result && res.data.data.result.length){
        let result=res.data.data.result;

        console.log('配件列表');
        console.log(result);

        let arr=[];
        result.forEach(item => {
          let str = "";
          item.specs.forEach(s => {
            str += s.key + "-" + s.value + " | ";
          });
          item.params.forEach(p => {
            str += p.key + "-" + p.value + " | ";
          });
          str = str.substr(0, str.length - 3);

          arr.push({
            text: item.name +'&'+ str,
            id: item.id,
            obj: item
          });
        });  

        this.setData({
          selectList: arr
        })
      }
    }).catch((error) => {
    })
  },  

  //获取厂家设备型号
  getFactoryEquipmentModel(){
    let param = {
      isAuth: true,
      className: 'factoryEquipmentType',
      data: {
        searchAll: true,
        selectFields: ['id', 'name']
      }
    }

    CommonService.goFindList(param).then(res=>{
      if(res.data.data && res.data.data.result && res.data.data.result.length){
        let result=res.data.data.result;
        let map=new Map();
        result.forEach(item => {
          map.set(item.id,item.name)
        });
        this.setData({
          factoryCategory: map
        })
      }
    }).catch((error) => {
    })
  },

  //获取配件输入的值
  onGetValue(e){
    let dataset=e.currentTarget.dataset;  
    let val=e.detail;
    let list=this.data.partList;

    list.forEach((item,index) => {
      if(index==dataset.index){
        item[dataset.field]=val.trim();
      }
    });

    this.setData({ 
      partList: list,
      disabled: false
		})
  },

  //获取配件数量
  onChangeNum(e) {
    let list=this.data.partList;
    let dataset=e.currentTarget.dataset;
    
    list.forEach((item,index) => {
      if(index==dataset.index){
        item.num=e.detail;
      }
    });

    this.setData({ 
      partList: list,
      disabled: false
		})
  },

  //添加配件
  onAddPart(){
    if(this.data.editInfo.factory){
      let list=this.data.partList;  

      //未填写不能加新的
      if(list.length){
        let len=list.length-1;
        if(list[len].name){
        }else{
          Toast.fail('当前配件信息未完成');
          return;
        }
      }

      list.push({
        code: null,
        name: null,
        specStr: null,
        brandsStr: null,
        unit: null,
        num: 1,
        purchasingPrice: null,
        salePrice: null,
      });  

      this.setData({ 
        partList: list 
      })
    }else{
      Toast.fail('请先选择配件厂家');
    }
  },

  //删除配件
  ondeletePart(e){
    Dialog.confirm({
      title: '确认删除此配件吗',
      confirmButtonText:'确认',
      cancelButtonText:'不删除了'
    }).then(() => {
      let list=this.data.partList;
      let dataset=e.currentTarget.dataset;
      let arr=[];
      
      list.forEach((item,index) => {
        if(index!=dataset.index){
          arr.push(item);
        }
      });
  
      this.setData({ 
        partList: arr 
      }) 
    }).catch(() => {
    });  
  },  

  //选择地区
  onChangeCities: function (e) {
    let cities='editInfo.cities';
    console.log(e.detail.value);
    this.setData({
      [cities]:e.detail.code,
      citiesName: e.detail.value,
      disabled:false
    })
  },

  //返回列表页并刷新数据
  backAndRefresh(){
    let pages = getCurrentPages();
    let prevPage = pages[pages.length - 2];

    prevPage.refreshListAndPage();
    wx.navigateBack();
  },

  //非空验证（field要先去掉空格）
  formNotEmpty(field,messageField,messageCon){
    if(!field){
      let obj = {};
      obj[messageField] = messageCon;
      obj['disabled'] = true;
      this.setData(obj);
      return false;
    }else{
      return true;
    }
  },

  //用户输入时清除错误提示
  clearMessage(e) {
    let field = e.target.dataset.message;
    let obj = {};
    obj[field] = "";
    obj['disabled'] = false;
    this.setData(obj);
  },

  //隐藏设置部门用友编码
  onCloseDepartCode(){
    this.setData({
      showDepartCode: false
    })
  },

  //获取部门用友编码
  onGetDepartCode(e){
    this.setData({
      departCode: e.detail,
    })
  },

  //保存部门用友编码
  onConfirmDepartCode(){
    let code=this.data.departCode;
    let selectField=this.data.selectField;
    let id=null;

    if(selectField=='client'){
      id=this.data.editInfo.clientDepart.id;
    }
    if(selectField=='project'){
      id=this.data.editInfo.project.id;
    }

    if(code){
      let param={
        className:'depart',
        data:{
          id: id,
          code: code
        }
      }

      CommonService.goSave(param).then(res=>{
        if (res.statusCode == 200 && res.data.success == true){
          Toast.success('编码已设置');

          let str='';
          if(selectField=='client'){
            str='editInfo.clientDepart.code';
          }
          if(selectField=='project'){
            str='editInfo.project.code';
          }
          
          this.setData({
            [str]: code
          })

          setTimeout(() => {
            this.onCloseDepartCode();
          }, 1000);
        }else{
          Toast.fail('操作失败');
        }
      }).catch((error) => {
        Toast.fail('操作失败');
      })
    }else{
      Toast.fail('请输入编码');
    }
  },

  //隐藏设置人员用友编码
  onCloseStaffCode(){
    this.setData({
      showStaffCode: false
    })
  },

  //保存人员用友编码
  onConfirmStaffCode(){
    let code=this.data.staffCode;  

    if(code){
      let param={
        className:'user',
        data:{
          id: this.data.editInfo.salesperson.id,
          code: code
        }
      }

      CommonService.goSave(param).then(res=>{
        if (res.statusCode == 200 && res.data.success == true){
          Toast.success('人员编码已设置');

          let str='editInfo.salesperson.code';        
          this.setData({
            [str]: code
          })

          setTimeout(() => {
            this.onCloseStaffCode();
          }, 1000);
        }else{
          Toast.fail('操作失败');
        }
      }).catch((error) => {
        Toast.fail('操作失败');
      })
    }else{
      Toast.fail('请输入编码');
    }
  },

  //查询厂家用友编码
  getFactoryCode(id,name){
    let param = {
      isAuth: false,
      className: 'depart',
      data: {
        id: id,
        selectFields: ['id','name','code']
      }
    }

    CommonService.goFindList(param).then(res=>{
      if(res.data.data && res.data.data.result && res.data.data.result.length){
        let result=res.data.data.result[0];
        
        let code='editInfo.factory.UFIDACode';
        this.setData({
          [code]: result.code ? result.code : null
        })
      }else{
        this.setData({
          showDepartCode: true,
          departName: name
        })
      }
    }).catch((error) => {
    })
  },

  //获取人员用友编码
  onGetStaffCode(e){
    this.setData({
      staffCode: e.detail,
    })
  },
  
  //建仓库
  getDepot(){
    let info=this.data.editInfo;
    let names=this.data.citiesName;

    let name=names[1];
    if (name.indexOf('市') > -1) {
        name = name.toString().substring(0, name.length - 1)
    }
    
    let param={
        "name": name+'仓',
        "cities": info.cities,
        "cityName": names[0] +'-'+ names[1] +'-'+ names[2]
    }

    CommonService.getDepot(param).then(res=>{
      if(res.statusCode == 200 && res.data.success == true){
      }else{
        Toast.fail('创建仓库或同步用友仓库失败，请联系管理员');
      }
    }).catch((error) => {
      Toast.fail('操作失败');
    }) 
  },

  //查询审批流
  getApprovalList(){
    this.setData({
      selectList: []
    })

    let param = {
      isAuth: true,
      className: 'workflowSetting',
      data: {
        'type.id': 226,
        searchAll: true,
        selectFields: ['id','name','type','approvalProcess']
      }
    }

    CommonService.goFindList(param).then(res=>{
      if(res.data.data && res.data.data.result && res.data.data.result.length){
        let result=res.data.data.result;
        console.log(result);
        let arr=[];
        result.forEach(item => {
          arr.push({
            text: item.name,
            id: item.id,
            obj: item
          });
        });
        this.setData({
          selectList: arr
        })
      }
    }).catch((error) => {
    })
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {

  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {

  }
})